package com.xc.exception;

import com.xc.utils.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author xingchen
 * @create 2021/10/24 20:36
 * 自定义异常处理器
 */
@ControllerAdvice
@Slf4j
public class CustomExceptionHandler {

    /**
     * 有Exception异常就会进到当前处理器
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonData handler(Exception e) {

        //判断是否是自定义的异常
        if (e instanceof BizException) {
            //强转
            BizException bizException= (BizException) e;
            log.error("[业务异常{}]",e);
            //返回前端
            return JsonData.buildCodeAndMsg(bizException.getCode(),bizException.getMsg());
        } else {
            log.error("[业务异常{}]",e);
            return JsonData.buildError("系统异常，未知错误");
        }

    }
}
